#include "StdAfx.h"
#include "ClientNetwork.h"
#define DEFAULT_BUFLEN 65536
#define DEFAULT_PORT "27015"



int tcpnodelay(int sock) {
    int yes=1;
    return setsockopt(sock,IPPROTO_TCP,TCP_NODELAY,(char*)&yes,sizeof(int));
}
 


ClientNetwork::ClientNetwork()
{
	//PORT
	this->portNumber=0;
	//IPAddress
	this->Server_Address = 0;	 
	
    
	 //SOCKET 
	 this->ConnectSocket = INVALID_SOCKET;

    result = NULL;
    ptr = NULL,

	//iResult
    this->iResult = 0;

    

    // Validate the parameters
    if (false) {
        printf("\nusage: %s server-name\n");
		system("pause");
        exit(1);
    }
 
    // Initialize Winsock
    iResult = WSAStartup(MAKEWORD(2,2), &wsaData);
    if (iResult != 0) {
        printf("\nWSAStartup failed with error: %d\n", iResult);
		system("pause");
		exit(1);
    }
 
    ZeroMemory( &hints, sizeof(hints) );
    hints.ai_family = AF_UNSPEC;
    hints.ai_socktype = SOCK_STREAM;
    hints.ai_protocol = IPPROTO_TCP;
 
}


ClientNetwork::~ClientNetwork()
{

	if(!this->ConnectSocket)
		this->CloseMyConnection();

}



int ClientNetwork::MyClientConnection(char *ServerAdd,int PortNumber)
{
	//PORT
	this->portNumber = PortNumber;
	char *port = new char[10];
	_itoa(PortNumber,port,10);


	//IPAddress
	this->Server_Address = new char[strlen(ServerAdd)+1];
	strcpy(this->Server_Address,ServerAdd);

	// Resolve the server address and port
	iResult = getaddrinfo(Server_Address, port , &hints, &result);
    if ( iResult != 0 ) 
	{
       // printf("getaddrinfo failed with error: %d\n", iResult);
        WSACleanup();
		//system("pause");
       // exit(1);
		throw new ConexiuneEronata("\n\ngetaddrinfo failed with error: %d\n", iResult);
    }


	// Attempt to connect to an address until one succeeds
    for(ptr=result; ptr != NULL ;ptr=ptr->ai_next) {
 
        // Create a SOCKET for connecting to server
        ConnectSocket = socket(ptr->ai_family, ptr->ai_socktype, 
            ptr->ai_protocol);
        if (ConnectSocket == INVALID_SOCKET) 
		{
			WSACleanup();
			throw new ConexiuneEronata("\n\nSocket esuat.\n",WSAGetLastError());
        }
 
        // Connect to server.
        iResult = connect( ConnectSocket, ptr->ai_addr, (int)ptr->ai_addrlen);
        if (iResult == SOCKET_ERROR) 
		{
            closesocket(ConnectSocket);
            ConnectSocket = INVALID_SOCKET;
            continue;
        }
        break;
    }
 
    freeaddrinfo(result);


	
    if (ConnectSocket == INVALID_SOCKET)
	{
        //printf("Incapabil sa se conecteze la server.\n");
        WSACleanup();
		throw new ConexiuneEronata("\n\nIncapabil sa se conecteze la server.\n",0);
    }
 
    if (tcpnodelay(ConnectSocket)<0) 
	{
		throw new ConexiuneEronata("\n\nNu poate seta TCP_NODELAY!\n",1);
    }

	return 0;

}

int ClientNetwork::sendPackets(char *buffer)
{

		sendbuf = new char[strlen(buffer)+1];
		strcpy(this->sendbuf,buffer);
	

	//Send data...
	   iResult = send(ConnectSocket, sendbuf, strlen(sendbuf), 0);
 
            if (iResult == SOCKET_ERROR) 
			{
                closesocket(ConnectSocket);
                WSACleanup();
				throw new ConexiuneEronata("\n\nSocket esuat.\n",WSAGetLastError());
			}
            
    printf("\n->Send data to Server! .... Bytes Sent: %ld", iResult);

	return 0;

}

int ClientNetwork::sendPackets(char *buffer,int size)
{
	//Send data...
	   iResult = send(ConnectSocket, buffer, size , 0);
 
            if (iResult == SOCKET_ERROR) 
			{
                closesocket(ConnectSocket);
                WSACleanup();
				throw new ConexiuneEronata("\n\nSocket esuat.\n",WSAGetLastError());
			}
            
    printf("\n\n ->Send data to Server! .... Bytes Sent: %ld", iResult);

	return 0;
}





int ClientNetwork::receivePackets(char *recvbuffer) 
{
	
	iResult=recv(ConnectSocket,recvbuf,strlen(recvbuf),0);

	
	if ( iResult == 0 )
    {
        closesocket(ConnectSocket);
        WSACleanup();
		throw new ConexiuneEronata("Conexiune inchisa.",0);
    }
	else
	{

		int i=0;

		while(recvbuf[i] != '*')
		{
			recvbuffer[i]=recvbuf[i];
			i++;
		}

		recvbuffer[i]='\0';
	}

    if ( iResult == 0 )
    {
        closesocket(ConnectSocket);
        WSACleanup();
		throw new ConexiuneEronata("Conexiune inchisa.",0);
    }

	int msj_length = strlen(recvbuffer);

	return msj_length;
}


int ClientNetwork::CloseMyConnection()
{
	  // shutdown the connection since no more data will be sent
    iResult = shutdown(ConnectSocket, SD_SEND);

    if (iResult == SOCKET_ERROR) {
        closesocket(ConnectSocket);
        WSACleanup();
		throw new ConexiuneEronata("\n\nSocket esuat.\n",WSAGetLastError());
    }
 
    // cleanup
    closesocket(ConnectSocket);
    WSACleanup();
	ConnectSocket = 0;

	printf("\n------------------------");
	system("pause");

    return 0;
}
